/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.bef.builtincomponents.UQConstraints;

import com.inspur.edp.bef.core.be.BEManager;
import com.inspur.edp.bef.core.scope.SingleBETypeExtension;
import com.inspur.edp.cef.api.message.BizMessage;
import com.inspur.edp.cef.api.message.IBizMessage;
import com.inspur.edp.cef.api.message.MessageLevel;
import com.inspur.edp.cef.api.message.MessageLocation;
import com.inspur.edp.cef.api.scope.ICefScopeNodeParameter;
import com.inspur.edp.cef.core.i18n.I18nResourceUtil;
import com.inspur.edp.cef.entity.UQConstraintConfig;
import com.inspur.edp.cef.entity.UQConstraintMediate;
import com.inspur.edp.cef.entity.accessor.base.AccessorComparer;
import com.inspur.edp.cef.entity.changeset.ModifyChangeDetail;
import com.inspur.edp.cef.entity.entity.IEntityData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.springframework.util.StringUtils;

public class QUConstraintValScopeExtension extends SingleBETypeExtension {

  @Override
  public void onExtendSetComplete() {
    BEManager beManager = (BEManager) getSessionItem().getBEManager();

    HashMap<String, UQConstraintItem> items = new HashMap<>();
    for (ICefScopeNodeParameter parameter : super.getParameters()) {
      AddParamToItems(items, (UQConstraintValParameter) parameter);
    }
    HashMap<String, ArrayList<UQConstraintMediate>> dict = new HashMap<>();
    for (Map.Entry<String, ArrayList<UQConstraintConfig>> item : beManager.getConstraintInfo()
        .entrySet()) {
      UQConstraintItem uqItem = items.get(item.getKey());
      if (uqItem == null) {
        continue;
      }
      for (UQConstraintConfig config : item.getValue()) {
        UQConstraintMediate mediate = GetUQConstraintMediate(uqItem.getAddedDatas(),
            uqItem.getModifiedDatas(), uqItem.getModifiedChanges(), uqItem.getDeletedDatas(),
            config, item.getKey());
        TryToAddConstraintmediateToDict(dict, mediate, item.getKey());
      }
    }
    beManager.getRepository().checkUniqueness(dict, false);

    for (Map.Entry<String, ArrayList<UQConstraintMediate>> pair : dict.entrySet()) {
      for (UQConstraintMediate mediate : pair.getValue()) {
        if (!mediate.getCheckFailed()) {
          continue;
        }

        addMessage(createMessage(pair.getKey(), buildI18nMessage(mediate.getMessage()),
            new ArrayList<>(mediate.getParametersInfo().keySet()),
            new ArrayList<>(mediate.getParametersInfo().values().iterator().next().keySet())));
      }
    }
  }

  private void TryToAddConstraintmediateToDict(
      HashMap<String, ArrayList<UQConstraintMediate>> dict,
      UQConstraintMediate mediate, String nodeCode) {
    ArrayList<UQConstraintMediate> list = dict.get(nodeCode);
    if(list == null) {
      dict.put(nodeCode, (list = new ArrayList<>()));
    }
    list.add(mediate);
  }

  private void AddParamToItems(HashMap<String, UQConstraintItem> items,
      UQConstraintValParameter parameter) {
    UQConstraintItem item = items.get(parameter.getNodeCode());
    if (item == null) {
      items.put(parameter.getNodeCode(), (item = new UQConstraintItem()));
    }
    switch (parameter.getChangeType()) {
      case Added:
        item.getAddedDatas().add(parameter.getChangeData());
        break;
      case Deleted:
        if (parameter.getChangeData() != null) {
          item.getDeletedDatas().add(parameter.getChangeData().getID());
        }
        break;
      case Modify:
        item.getModifiedDatas().add(parameter.getChangeData());
        break;
    }
  }

  private UQConstraintMediate GetUQConstraintMediate(ArrayList<IEntityData> add,
      ArrayList<IEntityData> modify, ArrayList<ModifyChangeDetail> modifyChange,
      ArrayList<String> deleteDataIds, UQConstraintConfig config, String nodeCode) {
    //排除没有任何约束字段修改的变更数据
    ArrayList<ModifyChangeDetail> changeList = new ArrayList<>();
    for (ModifyChangeDetail change : modifyChange) {
      boolean notContain = true;
      for (int i = 0; i < config.getConstraintFields().size(); i++) {
        if (change.getPropertyChanges().containsKey(config.getConstraintFields().get(i))) {
          notContain = false;
          break;
        }
      }
      if (notContain) {
        changeList.add(change);
        for (int i = 0; i < modify.size(); i++) {
          if (modify.get(i).getID().equals(change.getID())) {
            modify.remove(modify.get(i));
            break;
          }
        }
      }

    }
    for (ModifyChangeDetail item : changeList) {
      modifyChange.remove(item);
    }
    //将新增和修改的数据进行比较，如果有冲突则无需与数据库校验
    ArrayList<IEntityData> check = new ArrayList<>(add.size() + modify.size());
    check.addAll(add);
    check.addAll(modify);

    UQConstraintMediate result = new UQConstraintMediate();

    while (check.size() > 1) {
      Iterator<IEntityData> iterator = check.iterator();
      IEntityData current = iterator.next();
      iterator.remove();
      List<String> duplicatedList = new LinkedList();
      while (iterator.hasNext()) {
        IEntityData candidate = iterator.next();
        boolean valueEqual = true;
        for (int k = 0; k < config.getConstraintFields().size(); k++) {
          String field = config.getConstraintFields().get(k);
          Object currentValue = current.getValue(field);
          Object candidateValue = candidate.getValue(field);
          if(!AccessorComparer.equals(currentValue, candidateValue)) {
            valueEqual = false;
            break;
          }
        }
        if (valueEqual) {
          duplicatedList.add(candidate.getID());
          iterator.remove();
        }
      }
      if (!duplicatedList.isEmpty()) {
        duplicatedList.add(0, current.getID());
        String exceptionCode = StringUtils.isEmpty(config.getMessage()) ?
            getDefaultDisplayMessage() : config.getMessage();
        addMessage(
            createMessage(nodeCode, exceptionCode, duplicatedList, config.getConstraintFields()));
      } else {
        result.getParametersInfo().put(current.getID(), buildConstraintValues(config, current));
      }
    }
    if(!check.isEmpty()) {
      result.getParametersInfo()
          .put(check.get(0).getID(), buildConstraintValues(config, check.get(0)));
    }

    result.getExceptDeleteIds().addAll(deleteDataIds);

    result.getExceptModifyIds().ensureCapacity(modify.size());
    for (IEntityData data : modify) {
      result.getExceptModifyIds().add(data.getID());
    }

    result.setMessage(config.getMessage());

    return result;
  }

  private HashMap<String, Object> buildConstraintValues(UQConstraintConfig config, IEntityData data) {
    HashMap<String, Object> value = new HashMap<>((int)(config.getConstraintFields().size()/0.75+1));
    for (String field : config.getConstraintFields()) {
      value.put(field, data.getValue(field));
    }
    return value;
  }

  private String defaultDisplayMsg;

  private synchronized String getDefaultDisplayMessage() {
    if (defaultDisplayMsg == null) {
      defaultDisplayMsg = I18nResourceUtil.getResourceItemValue(
          "pfcommon", "cef_exception.properties", "Gsp_Bef_UQVal_0001");
    }
    return defaultDisplayMsg;
  }

  private String buildI18nMessage(String message) {
    return StringUtils.isEmpty(message) ? getDefaultDisplayMessage() : message;
  }

  public IBizMessage createMessage(String nodeCode, String msg, List<String> dataIds,
      List<String> columns) {
    return new BizMessage() {{
      setMessageFormat(msg);
      setLevel(MessageLevel.Error);
      setLocation(new MessageLocation() {{
        setDataIds(dataIds);
        setNodeCode(nodeCode);
        setColumnNames(columns);
      }});
    }};
  }
}
